/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    //定制资源映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //意思是：url中读取到/upload时，就会自动将/upload解析成D:/idea/java_workspace/image/upload
        registry.addResourceHandler("/image/**").addResourceLocations("file:D:/JT_IMAGE");
        /**
         * Linux系统
         * registry.addResourceHandler("/upload/**").addResourceLocations("file:/home/image/upload/");
         */
    }
    @Bean
    public CorsFilter corsFilter() {
        // 初始化cors配置对象
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许跨域的域名，如果要携带cookie，不能写*，*代表所有域名都可以跨域访问
//        corsConfiguration.addAllowedOrigin("http://localhost:10008");
        // 本机使用nginx测试
        corsConfiguration.addAllowedOrigin("http://localhost:8001");
        //Access-Control-Allow-Origin
//        corsConfiguration.addAllowedOrigin("http://localhost:8778");
        corsConfiguration.setAllowCredentials(true);    // 允许携带cookies
        corsConfiguration.addAllowedMethod("*");    // 代表所有的请求方法：get、post、put、delete
        corsConfiguration.addAllowedHeader("*");    // 允许携带任何头信息
        // 初始化cors配置源对象
        UrlBasedCorsConfigurationSource configurationSource = new   UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**",corsConfiguration);

        // 返回corsFilter实例，参数：cors配置源对象
        return new CorsFilter(configurationSource);
    }

}